using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DesktopWidgetApp.Server.Models;
using Microsoft.EntityFrameworkCore;

namespace DesktopWidgetApp.Server.Services
{
    /// <summary>
    /// 团队服务实现
    /// 提供团队管理的具体功能实现
    /// </summary>
    public class TeamService : ITeamService
    {
        private readonly AppDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public TeamService(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 创建新团队
        /// </summary>
        /// <param name="teamName">团队名称</param>
        /// <param name="description">团队描述</param>
        /// <param name="creatorId">创建者ID</param>
        /// <returns>创建结果</returns>
        public async Task<(bool success, string message, Team team)> CreateTeamAsync(string teamName, string description, Guid creatorId)
        {
            try
            {
                // 验证团队名称
                if (string.IsNullOrWhiteSpace(teamName))
                {
                    return (false, "团队名称不能为空", null);
                }

                // 验证创建者存在
                var creator = await _dbContext.Users.FindAsync(creatorId);
                if (creator == null)
                {
                    return (false, "创建者不存在", null);
                }

                // 创建新团队
                var team = new Team
                {
                    Id = Guid.NewGuid(),
                    Name = teamName.Trim(),
                    Description = description?.Trim(),
                    CreatedAt = DateTime.Now,
                    CreatorId = creatorId
                };

                // 添加创建者为团队成员，并设置为管理员角色
                var teamMember = new TeamMember
                {
                    TeamId = team.Id,
                    UserId = creatorId,
                    Role = "Admin",
                    JoinedAt = DateTime.Now
                };

                _dbContext.Teams.Add(team);
                _dbContext.TeamMembers.Add(teamMember);
                await _dbContext.SaveChangesAsync();

                return (true, "团队创建成功", team);
            }
            catch (Exception ex)
            {
                return (false, $"创建团队失败：{ex.Message}", null);
            }
        }

        /// <summary>
        /// 获取团队列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户所属的团队列表</returns>
        public async Task<IEnumerable<Team>> GetUserTeamsAsync(Guid userId)
        {
            return await _dbContext.Teams
                .Where(t => t.Members.Any(m => m.UserId == userId))
                .OrderByDescending(t => t.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 获取团队详情
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>团队详情</returns>
        public async Task<Team?> GetTeamByIdAsync(Guid teamId)
        {
            return await _dbContext.Teams
                .Include(t => t.Members)
                .ThenInclude(m => m.User)
                .FirstOrDefaultAsync(t => t.Id == teamId);
        }

        /// <summary>
        /// 更新团队信息
        /// </summary>
        /// <param name="team">团队对象</param>
        /// <returns>更新结果</returns>
        public async Task<(bool success, string message)> UpdateTeamAsync(Team team)
        {
            try
            {
                if (team == null)
                {
                    return (false, "团队信息不能为空");
                }

                if (string.IsNullOrWhiteSpace(team.Name))
                {
                    return (false, "团队名称不能为空");
                }

                var existingTeam = await _dbContext.Teams.FindAsync(team.Id);
                if (existingTeam == null)
                {
                    return (false, "团队不存在");
                }

                // 更新团队信息
                existingTeam.Name = team.Name.Trim();
                existingTeam.Description = team.Description?.Trim();

                _dbContext.Teams.Update(existingTeam);
                await _dbContext.SaveChangesAsync();

                return (true, "团队信息更新成功");
            }
            catch (Exception ex)
            {
                return (false, $"更新团队信息失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除团队
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="requestorId">请求者ID</param>
        /// <returns>删除结果</returns>
        public async Task<(bool success, string message)> DeleteTeamAsync(Guid teamId, Guid requestorId)
        {
            try
            {
                var team = await _dbContext.Teams.FindAsync(teamId);
                if (team == null)
                {
                    return (false, "团队不存在");
                }

                // 检查请求者是否为团队创建者
                if (team.CreatorId != requestorId)
                {
                    return (false, "只有团队创建者才能删除团队");
                }

                // 先删除所有团队成员
                var teamMembers = await _dbContext.TeamMembers
                    .Where(tm => tm.TeamId == teamId)
                    .ToListAsync();

                _dbContext.TeamMembers.RemoveRange(teamMembers);
                _dbContext.Teams.Remove(team);
                await _dbContext.SaveChangesAsync();

                return (true, "团队删除成功");
            }
            catch (Exception ex)
            {
                return (false, $"删除团队失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 添加团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <param name="role">成员角色</param>
        /// <param name="requestorId">请求者ID</param>
        /// <returns>添加结果</returns>
        public async Task<(bool success, string message)> AddTeamMemberAsync(Guid teamId, Guid userId, string role, Guid requestorId)
        {
            try
            {
                var team = await _dbContext.Teams.FindAsync(teamId);
                if (team == null)
                {
                    return (false, "团队不存在");
                }

                var user = await _dbContext.Users.FindAsync(userId);
                if (user == null)
                {
                    return (false, "用户不存在");
                }

                // 检查请求者是否为团队管理员或创建者
                var requestorRole = await GetUserRoleInTeamAsync(teamId, requestorId);
                if (requestorRole == null || (requestorRole != "Admin" && requestorId != team.CreatorId))
                {
                    return (false, "只有团队管理员或创建者才能添加成员");
                }

                // 检查用户是否已经是团队成员
                var existingMember = await _dbContext.TeamMembers
                    .FirstOrDefaultAsync(tm => tm.TeamId == teamId && tm.UserId == userId);
                if (existingMember != null)
                {
                    return (false, "用户已经是团队成员");
                }

                // 添加新成员
                var newMember = new TeamMember
                {
                    TeamId = teamId,
                    UserId = userId,
                    Role = string.IsNullOrWhiteSpace(role) ? "Member" : role.Trim(),
                    JoinedAt = DateTime.Now
                };

                _dbContext.TeamMembers.Add(newMember);
                await _dbContext.SaveChangesAsync();

                return (true, "成员添加成功");
            }
            catch (Exception ex)
            {
                return (false, $"添加成员失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 移除团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <param name="requestorId">请求者ID</param>
        /// <returns>移除结果</returns>
        public async Task<(bool success, string message)> RemoveTeamMemberAsync(Guid teamId, Guid userId, Guid requestorId)
        {
            try
            {
                var team = await _dbContext.Teams.FindAsync(teamId);
                if (team == null)
                {
                    return (false, "团队不存在");
                }

                // 检查用户是否为团队成员
                var member = await _dbContext.TeamMembers
                    .FirstOrDefaultAsync(tm => tm.TeamId == teamId && tm.UserId == userId);
                if (member == null)
                {
                    return (false, "用户不是团队成员");
                }

                // 检查权限
                // 1. 团队创建者可以移除任何人
                // 2. 团队管理员可以移除非管理员成员
                // 3. 用户可以自行离开团队
                var requestorRole = await GetUserRoleInTeamAsync(teamId, requestorId);
                if (requestorId != team.CreatorId && 
                    !(requestorRole == "Admin" && member.Role != "Admin") && 
                    requestorId != userId)
                {
                    return (false, "没有权限移除该成员");
                }

                _dbContext.TeamMembers.Remove(member);
                await _dbContext.SaveChangesAsync();

                return (true, "成员移除成功");
            }
            catch (Exception ex)
            {
                return (false, $"移除成员失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取团队成员列表
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>团队成员列表</returns>
        public async Task<IEnumerable<TeamMember>> GetTeamMembersAsync(Guid teamId)
        {
            return await _dbContext.TeamMembers
                .Where(tm => tm.TeamId == teamId)
                .Include(tm => tm.User)
                .ToListAsync();
        }

        /// <summary>
        /// 检查用户是否为团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>是否为成员</returns>
        public async Task<bool> IsUserInTeamAsync(Guid teamId, Guid userId)
        {
            return await _dbContext.TeamMembers
                .AnyAsync(tm => tm.TeamId == teamId && tm.UserId == userId);
        }

        /// <summary>
        /// 检查用户在团队中的角色
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>角色名称，如果不是团队成员则返回null</returns>
        public async Task<string?> GetUserRoleInTeamAsync(Guid teamId, Guid userId)
        {
            var member = await _dbContext.TeamMembers
                .FirstOrDefaultAsync(tm => tm.TeamId == teamId && tm.UserId == userId);
            return member?.Role;
        }
    }
}